﻿/*---------------------------------------------------------------------------------
-----------------***DaLianQianYi***-----------------------
-----------------作者：大连仟亿科技------------------------------------------------------
-----------------联系作者：www.qianyikeji.com----------------------------------
-----------------时间：2018/5/2 19:31:32------------------------------------------
----------------------------------------------------------------------------------*/


using Donal.Xms.Common;
using Donal.Xms.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;

namespace Donal.Xms.DAL
{
    /// <summary>
    /// 数据访问类
    /// </summary>
    public partial class company
    {
        private string databaseprefix; //数据库表名前缀
        public company(string _databaseprefix)
        {
            databaseprefix = _databaseprefix;
        }

        #region 基本方法================================
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from  dt_company");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
                        new SqlParameter("@id", SqlDbType.Int,10)};
            parameters[0].Value = id;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool ExistsCompany(string companyName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from  dt_company");
            strSql.Append(" where companyName=@companyName");
            SqlParameter[] parameters = {
                        new SqlParameter("@companyName", SqlDbType.NVarChar,200)};
            parameters[0].Value = companyName;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string erpCode)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from  dt_company");
            strSql.Append(" where erpCode=@erpCode");
            SqlParameter[] parameters = {
                        new SqlParameter("@erpCode", SqlDbType.NVarChar,50)};
            parameters[0].Value = erpCode;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Model.company model)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();//数据字段
            StringBuilder str2 = new StringBuilder();//数据参数
                                                     //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            List<SqlParameter> paras = new List<SqlParameter>();
            strSql.Append("insert into " + databaseprefix + "company(");
            foreach (PropertyInfo pi in pros)
            {
                //如果不是主键则追加sql字符串
                if (!pi.Name.Equals("id"))
                {
                    //判断属性值是否为空
                    if (pi.GetValue(model, null) != null)
                    {
                        str1.Append(pi.Name + ",");//拼接字段
                        str2.Append("@" + pi.Name + ",");//声明参数
                        paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                    }
                }
            }
            strSql.Append(str1.ToString().Trim(','));
            strSql.Append(") values (");
            strSql.Append(str2.ToString().Trim(','));
            strSql.Append(") ");
            strSql.Append(";select @@IDENTITY;");
            object obj = DbHelperSQL.GetSingle(strSql.ToString(), paras.ToArray());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                if (model.status == 0)
                {
                    DbHelperSQL.ExecuteSql("INSERT INTO [dbo].[dt_audit_times]([audit_time],[audit_type],[user_id]) values('" + DateTime.Now.ToString() + "',0," + model.id + ")");
                }
                return Convert.ToInt32(obj);
            }
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(SqlConnection conn, SqlTransaction trans, Model.company model)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();//数据字段
            StringBuilder str2 = new StringBuilder();//数据参数
                                                     //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            List<SqlParameter> paras = new List<SqlParameter>();
            strSql.Append("insert into " + databaseprefix + "company(");
            foreach (PropertyInfo pi in pros)
            {
                //如果不是主键则追加sql字符串
                if (!pi.Name.Equals("id"))
                {
                    //判断属性值是否为空
                    if (pi.GetValue(model, null) != null)
                    {
                        str1.Append(pi.Name + ",");//拼接字段
                        str2.Append("@" + pi.Name + ",");//声明参数
                        paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                    }
                }
            }
            strSql.Append(str1.ToString().Trim(','));
            strSql.Append(") values (");
            strSql.Append(str2.ToString().Trim(','));
            strSql.Append(") ");
            strSql.Append(";select @@IDENTITY;");
            object obj = DbHelperSQL.GetSingle(conn, trans, strSql.ToString(), paras.ToArray());

            if (obj == null)
            {
                return 0;
            }
            else
            {
                if (model.status == 0)
                {
                    DbHelperSQL.ExecuteSql(conn, trans, "INSERT INTO [dbo].[dt_audit_times]([audit_time],[audit_type],[user_id]) values('" + DateTime.Now.ToString() + "',0," + model.id + ")");
                }

                return Convert.ToInt32(obj);
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.company model)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        StringBuilder strSql = new StringBuilder();
                        StringBuilder str1 = new StringBuilder();
                        //利用反射获得属性的所有公共属性
                        PropertyInfo[] pros = model.GetType().GetProperties();
                        List<SqlParameter> paras = new List<SqlParameter>();
                        strSql.Append("update  " + databaseprefix + "company set ");
                        foreach (PropertyInfo pi in pros)
                        {
                            //如果不是主键则追加sql字符串
                            if (!pi.Name.Equals("id"))
                            {
                                //判断属性值是否为空
                                if (pi.GetValue(model, null) != null)
                                {
                                    str1.Append(pi.Name + "=@" + pi.Name + ",");//声明参数
                                    paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                                }
                            }
                        }
                        strSql.Append(str1.ToString().Trim(','));
                        strSql.Append(" where id=@id ");
                        paras.Add(new SqlParameter("@id", model.id));

                        int v = DbHelperSQL.ExecuteSql(strSql.ToString(), paras.ToArray());


                        trans.Rollback();
                        conn.Close();
                        return false;

                    }
                    catch (Exception e)
                    {
                        Utils.WriteLogs("同步会员到ERP异常：", e.Message + e.StackTrace, "", DTKeys.EXCEPION_PATH);
                        trans.Rollback();
                        conn.Close();
                        return false;
                    }
                }
            }
        }


        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.company model, bool isAddAudit, int ismaster)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        StringBuilder strSql = new StringBuilder();
                        StringBuilder str1 = new StringBuilder();
                        //利用反射获得属性的所有公共属性
                        PropertyInfo[] pros = model.GetType().GetProperties();
                        List<SqlParameter> paras = new List<SqlParameter>();
                        strSql.Append("update  " + databaseprefix + "company set ");
                        foreach (PropertyInfo pi in pros)
                        {
                            if (ismaster == 1)
                            {
                                //如果不是主键则追加sql字符串
                                if (!pi.Name.Equals("id"))
                                {
                                    //判断属性值是否为空
                                    if (pi.GetValue(model, null) != null)
                                    {
                                        str1.Append(pi.Name + "=@" + pi.Name + ",");//声明参数
                                        paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                                    }
                                }
                            }
                            else//不是管理员，不能更新会员的账户余额，积分，信用额度
                            {
                                //如果不是主键则追加sql字符串
                                if (!pi.Name.Equals("id") && !pi.Name.Equals("amount") && !pi.Name.Equals("point") && !pi.Name.Equals("credit"))
                                {
                                    //判断属性值是否为空
                                    if (pi.GetValue(model, null) != null)
                                    {
                                        str1.Append(pi.Name + "=@" + pi.Name + ",");//声明参数
                                        paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                                    }
                                }
                            }

                        }
                        strSql.Append(str1.ToString().Trim(','));
                        strSql.Append(" where id=@id ");
                        paras.Add(new SqlParameter("@id", model.id));

                        int v = DbHelperSQL.ExecuteSql(conn, trans, strSql.ToString(), paras.ToArray());


                        try
                        {
                            if (model.status == 0)
                            {
                                DAL.last_time ltDal = new last_time(databaseprefix);

                                Model.last_time last_Time = ltDal.GetModel(conn, trans, model.id);

                                if (last_Time != null)
                                {
                                    last_Time.lastTime = DateTime.Now;

                                    ltDal.Update(conn, trans, last_Time);
                                }
                                else
                                {
                                    ltDal.Add(conn, trans, new Model.last_time() { lastTime = DateTime.Now, erpCode = "" });
                                }
                            }
                        }
                        catch { }


                        if (v > 0)
                        {
                            if (new budyy_no_index(databaseprefix).Add(conn, trans, new Model.budyy_no_index() { erp_code = "" }) > 0)
                            {
                                if (isAddAudit)
                                {
                                    DbHelperSQL.GetSingle(conn, trans, "INSERT INTO [dbo].[dt_audit_times]([audit_time],[audit_type],[user_id]) values('" + DateTime.Now.ToString() + "'," + model.status + "," + model.id + ")");
                                }

                                trans.Commit();
                                conn.Close();
                                return true;
                            }
                        }


                        trans.Rollback();
                        conn.Close();
                        return false;

                    }
                    catch (Exception e)
                    {
                        Utils.WriteLogs("同步会员到ERP异常：", e.Message + e.StackTrace, "", DTKeys.EXCEPION_PATH);
                        trans.Rollback();
                        conn.Close();
                        return false;
                    }
                }
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(SqlConnection conn, SqlTransaction trans, Model.company model)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            List<SqlParameter> paras = new List<SqlParameter>();
            strSql.Append("update  " + databaseprefix + "company set ");
            foreach (PropertyInfo pi in pros)
            {
                //如果不是主键则追加sql字符串
                if (!pi.Name.Equals("id"))
                {
                    //判断属性值是否为空
                    if (pi.GetValue(model, null) != null)
                    {
                        str1.Append(pi.Name + "=@" + pi.Name + ",");//声明参数
                        paras.Add(new SqlParameter("@" + pi.Name, pi.GetValue(model, null)));//对参数赋值
                    }
                }
            }
            strSql.Append(str1.ToString().Trim(','));
            strSql.Append(" where id=@id ");
            paras.Add(new SqlParameter("@id", model.id));

            return DbHelperSQL.ExecuteSql(conn, trans, strSql.ToString(), paras.ToArray()) > 0;
        }


        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int id)
        {
            List<CommandInfo> sqllist = new List<CommandInfo>();
            //删除积分获取记录
            StringBuilder strSql1 = new StringBuilder();
            strSql1.Append("delete from " + databaseprefix + "points_logs");
            strSql1.Append(" where user_id=@id");
            SqlParameter[] parameters1 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters1[0].Value = id;
            CommandInfo cmd = new CommandInfo(strSql1.ToString(), parameters1);
            sqllist.Add(cmd);

            //删除积分使用记录
            StringBuilder strSql0 = new StringBuilder();
            strSql0.Append("delete from " + databaseprefix + "points_used");
            strSql0.Append(" where user_id=@id");
            SqlParameter[] parameters0 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters0[0].Value = id;
            cmd = new CommandInfo(strSql0.ToString(), parameters0);
            sqllist.Add(cmd);

            //删除金额记录
            StringBuilder strSql2 = new StringBuilder();
            strSql2.Append("delete from " + databaseprefix + "user_amount_log");
            strSql2.Append(" where user_id=@id");
            SqlParameter[] parameters2 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters2[0].Value = id;
            cmd = new CommandInfo(strSql2.ToString(), parameters2);
            sqllist.Add(cmd);

            //删除附件购买记录
            StringBuilder strSql3 = new StringBuilder();
            strSql3.Append("delete from " + databaseprefix + "user_attach_log");
            strSql3.Append(" where user_id=@id");
            SqlParameter[] parameters3 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters3[0].Value = id;
            cmd = new CommandInfo(strSql3.ToString(), parameters3);
            sqllist.Add(cmd);

            //删除申请码
            StringBuilder strSql5 = new StringBuilder();
            strSql5.Append("delete from " + databaseprefix + "user_code");
            strSql5.Append(" where user_id=@id");
            SqlParameter[] parameters5 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters5[0].Value = id;
            cmd = new CommandInfo(strSql5.ToString(), parameters5);
            sqllist.Add(cmd);

            //删除登录日志
            StringBuilder strSql6 = new StringBuilder();
            strSql6.Append("delete from " + databaseprefix + "user_login_log");
            strSql6.Append(" where user_id=@id");
            SqlParameter[] parameters6 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters6[0].Value = id;
            cmd = new CommandInfo(strSql6.ToString(), parameters6);
            sqllist.Add(cmd);

            //删除用户地址簿
            StringBuilder strSql7 = new StringBuilder();
            strSql7.Append("delete from " + databaseprefix + "user_addr_book");
            strSql7.Append(" where user_id=@id");
            SqlParameter[] parameters7 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters7[0].Value = id;
            cmd = new CommandInfo(strSql7.ToString(), parameters7);
            sqllist.Add(cmd);

            //删除OAuth授权用户信息
            StringBuilder strSql8 = new StringBuilder();
            strSql8.Append("delete from " + databaseprefix + "user_oauth");
            strSql8.Append(" where user_id=@id");
            SqlParameter[] parameters8 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters8[0].Value = id;
            cmd = new CommandInfo(strSql8.ToString(), parameters8);
            sqllist.Add(cmd);

            //删除用户充值表
            StringBuilder strSql9 = new StringBuilder();
            strSql9.Append("delete from " + databaseprefix + "user_recharge");
            strSql9.Append(" where user_id=@id");
            SqlParameter[] parameters9 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters9[0].Value = id;
            cmd = new CommandInfo(strSql9.ToString(), parameters9);
            sqllist.Add(cmd);


            //删除账号表
            StringBuilder strSql10 = new StringBuilder();
            strSql10.Append("delete from  " + databaseprefix + "users");
            strSql10.Append(" where parent_id=@id");
            SqlParameter[] parameters10 = {
                    new SqlParameter("@id", SqlDbType.Int,10)};
            parameters10[0].Value = id;
            cmd = new CommandInfo(strSql10.ToString(), parameters10);
            sqllist.Add(cmd);


            //删除主表
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from  " + databaseprefix + "company ");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
                        new SqlParameter("@id", SqlDbType.Int,10)};
            parameters[0].Value = id;
            cmd = new CommandInfo(strSql.ToString(), parameters);
            sqllist.Add(cmd);


            return DbHelperSQL.ExecuteSqlTran(sqllist) > 0;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.company GetModel(int id)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            Model.company model = new Model.company();
            //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            foreach (PropertyInfo p in pros)
            {
                if (!typeof(System.Collections.IList).IsAssignableFrom(p.PropertyType))
                {
                    str1.Append(p.Name + ",");//拼接字段
                }
            }
            strSql.Append("select top 1 " + str1.ToString().Trim(','));
            strSql.Append(" from dt_company");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
                        new SqlParameter("@id", SqlDbType.Int,10)};
            parameters[0].Value = id;
            DataTable dt = DbHelperSQL.Query(strSql.ToString(), parameters).Tables[0];

            if (dt.Rows.Count > 0)
            {
                return DataRowToModel(dt.Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.company GetModel(string erpCode)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            Model.company model = new Model.company();
            //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            foreach (PropertyInfo p in pros)
            {
                if (!typeof(System.Collections.IList).IsAssignableFrom(p.PropertyType))
                {
                    str1.Append(p.Name + ",");//拼接字段
                }
            }
            strSql.Append("select top 1 " + str1.ToString().Trim(','));
            strSql.Append(" from dt_company");
            strSql.Append(" where erpCode=@erpCode");
            SqlParameter[] parameters = {
                        new SqlParameter("@erpCode", SqlDbType.NVarChar,50)};
            parameters[0].Value = erpCode;
            DataTable dt = DbHelperSQL.Query(strSql.ToString(), parameters).Tables[0];

            if (dt.Rows.Count > 0)
            {
                return DataRowToModel(dt.Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.company GetModel(SqlConnection conn, SqlTransaction trans, int buddy_id)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            Model.company model = new Model.company();
            //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            foreach (PropertyInfo p in pros)
            {
                if (!typeof(System.Collections.IList).IsAssignableFrom(p.PropertyType))
                {
                    str1.Append(p.Name + ",");//拼接字段
                }
            }
            strSql.Append("select top 1 " + str1.ToString().Trim(','));
            strSql.Append(" from dt_company");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
                        new SqlParameter("@id", SqlDbType.Int,8)};
            parameters[0].Value = buddy_id;
            DataTable dt = DbHelperSQL.Query(conn, trans, strSql.ToString(), parameters).Tables[0];

            if (dt.Rows.Count > 0)
            {
                return DataRowToModel(dt.Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.company GetModel(SqlConnection conn, SqlTransaction trans, string erpCode)
        {
            StringBuilder strSql = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            Model.company model = new Model.company();
            //利用反射获得属性的所有公共属性
            PropertyInfo[] pros = model.GetType().GetProperties();
            foreach (PropertyInfo p in pros)
            {
                if (!typeof(System.Collections.IList).IsAssignableFrom(p.PropertyType))
                {
                    str1.Append(p.Name + ",");//拼接字段
                }
            }
            strSql.Append("select top 1 " + str1.ToString().Trim(','));
            strSql.Append(" from dt_company");
            strSql.Append(" where erpCode=@erpCode");
            SqlParameter[] parameters = {
                        new SqlParameter("@erpCode", SqlDbType.NVarChar,50)};
            parameters[0].Value = erpCode;
            DataTable dt = DbHelperSQL.Query(conn, trans, strSql.ToString(), parameters).Tables[0];

            if (dt.Rows.Count > 0)
            {
                return DataRowToModel(dt.Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" * ");
            strSql.Append(" FROM dt_company");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(SqlConnection conn, SqlTransaction trans, int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" * ");
            strSql.Append(" FROM dt_company");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(conn, trans, strSql.ToString());
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public DataSet GetList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * FROM dt_company");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
            return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public DataSet GetListView(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * FROM view_company_infor v ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
            return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        }
        #endregion

        #region 扩展方法================================

        /// <summary>
        /// 获取溢价名称
        /// </summary>
        /// <param name="isUser">0会员 1组别</param>
        /// <param name="modelId">会员或组别ID</param>
        public string GetPremiumTitle(int isUser, int modelId)
        {
            if (isUser == 0)
            {
                return GetValue(modelId, "companyName");
            }
            else
            {
                return new DAL.user_groups("dt_").GetTitle(modelId);
            }
        }

        /// <summary>
        /// 返回指定列
        /// </summary>
        public string GetValue(int id, string fileName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 1 " + fileName + " from dt_company");
            strSql.Append(" where id=" + id);
            string title = Convert.ToString(DbHelperSQL.GetSingle(strSql.ToString()));
            if (string.IsNullOrEmpty(title))
            {
                return "";
            }
            return title;
        }

        /// <summary>
        /// 返回指定列
        /// </summary>
        public string GetValue(string erpCode, string fileName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 1 " + fileName + " from dt_company");
            strSql.Append(" where erpCode='" + erpCode + "'");
            string title = Convert.ToString(DbHelperSQL.GetSingle(strSql.ToString()));
            if (string.IsNullOrEmpty(title))
            {
                return "";
            }
            return title;
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(int id, string strValue)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + databaseprefix + "company set " + strValue);
            strSql.Append(" where id=" + id);
            return DbHelperSQL.ExecuteSql(strSql.ToString()) > 0;
        }

        public bool UpdateField(SqlConnection conn, SqlTransaction trans, int id, string strValue)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + databaseprefix + "company set " + strValue);
            strSql.Append(" where id=" + id);
            return DbHelperSQL.ExecuteSql(conn, trans, strSql.ToString()) > 0;
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateFieldFlow(decimal value, string companyCode, string operators, string remark, int flowType, int flowCase)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        Model.company company = new company(databaseprefix).GetModel(conn, trans, companyCode);
                        if (company == null)
                        {
                            trans.Rollback();
                            conn.Close();

                            Utils.WriteLogs("更新与添加优惠券信息时出错", "没有找到 ERPCODE=" + companyCode + " 的会员信息", companyCode, DTKeys.EXCEPION_PATH);
                            return false;
                        }

                        string v = new cash_flow(databaseprefix).FlowAction(conn, trans, value, companyCode, operators, 0, "", remark, flowType, flowCase, true);
                        if (v != "")
                        {
                            trans.Rollback();
                            Utils.WriteLogs("流水添加失败，导致会员充值失败！", v, "", DTKeys.EXCEPION_PATH);
                            return false;
                        }

                        if (flowType == 0)//只有账户充值时，才会处发是否发优惠券
                        {
                            //查找启用状态下的订单活动
                            List<Model.actions> actions = new actions(databaseprefix).GetModelList(conn, trans, " (category=0 or category=2) and status=1 and action_type=1  and ((DATEDIFF(DAY,getdate(),start_time)<=0 and DATEDIFF(DAY,getdate(),end_time)>=0) or expiration_form !=0) and conditions_amount <= " + value);

                            if (actions != null && actions.Count > 0)
                            {
                                List<Model.actions> newActions = new List<Model.actions>();

                                List<Model.actions> temActions = actions.FindAll(a => a.conditions_amount == value);
                                if (temActions != null && temActions.Count > 0)
                                {
                                    newActions = temActions;
                                }
                                else
                                {
                                    newActions.Add(actions[0]);
                                }
                                Dictionary<int, int> dic_coupon_quantity = new Dictionary<int, int>();
                                coupons coupDal = new coupons(databaseprefix);
                                foreach (Model.actions a in newActions)
                                {
                                    if (a.conditions_amount <= value)
                                    {
                                        string ids = "";
                                        if (a.coupons.Count > 0)
                                        {
                                            foreach (Model.action_coupons ac in a.coupons)
                                            {
                                                if (!dic_coupon_quantity.ContainsKey(ac.coupon_id))
                                                {
                                                    dic_coupon_quantity.Add(ac.coupon_id, ac.quantity);
                                                }
                                                else
                                                {
                                                    dic_coupon_quantity[ac.coupon_id] += ac.quantity;
                                                }
                                                ids += ac.coupon_id + ",";
                                            }
                                        }

                                        if (ids != "")
                                        {
                                            ids = ids.Substring(0, ids.Length - 1);
                                        }

                                        List<Model.coupons> coupons = coupDal.GetModelList(conn, trans, ids);

                                        if (coupons != null && coupons.Count > 0)
                                        {
                                            foreach (Model.coupons c in coupons)
                                            {
                                                string overTime = "";
                                                switch (c.expiration_form)
                                                {
                                                    case 0:
                                                        overTime = c.end_time.ToString();
                                                        break;
                                                    case 1:
                                                        overTime = DateTime.Now.AddDays(c.expiration_num).ToString();
                                                        break;
                                                    case 2:
                                                        overTime = "";
                                                        break;
                                                }

                                                //添加分配表
                                                for (int i = 0; i < dic_coupon_quantity[c.id]; i++)
                                                {
                                                    new coupons_allotment(databaseprefix).Add(conn, trans, new Model.coupons_allotment()
                                                    {
                                                        add_time = c.add_time,
                                                        allotment_time = DateTime.Now,
                                                        amount = c.amount,
                                                        conditions_amount = c.conditions_amount,
                                                        contents = c.contents,
                                                        coupon_id = c.id,
                                                        coupon_ids = c.coupon_ids,
                                                        end_time = c.end_time,
                                                        expiration_form = c.expiration_form,
                                                        expiration_num = c.expiration_num,
                                                        is_lock = 0,
                                                        order_no = "",
                                                        over_time = overTime,
                                                        sort_id = c.sort_id,
                                                        start_time = c.start_time,
                                                        status = c.status,
                                                        superposition = c.superposition,
                                                        title = c.title,
                                                        user_id = company.id
                                                    }, 3, companyCode, "", "用户充值获取优惠券");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        trans.Commit();
                    }
                    catch (Exception e)
                    {
                        trans.Rollback();
                        conn.Close();
                        Utils.WriteLogs("会员充值异常：", e.Message + e.StackTrace, companyCode, DTKeys.EXCEPION_PATH);
                        return false;
                    }
                }
                conn.Close();
                return true;
            }

        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(string code, string strValue)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + databaseprefix + "company set " + strValue);
            strSql.Append(" where erpCode='" + code + "'");
            return DbHelperSQL.ExecuteSql(strSql.ToString()) > 0;
        }

        /// <summary>
        /// 将对象转换实体
        /// </summary>
        public Model.company DataRowToModel(DataRow row)
        {
            Model.company model = new Model.company();
            if (row != null)
            {
                //利用反射获得属性的所有公共属性
                Type modelType = model.GetType();
                for (int i = 0; i < row.Table.Columns.Count; i++)
                {
                    //查找实体是否存在列表相同的公共属性
                    PropertyInfo proInfo = modelType.GetProperty(row.Table.Columns[i].ColumnName);
                    if (proInfo != null && row[i] != DBNull.Value)
                    {
                        proInfo.SetValue(model, row[i], null);//用索引值设置属性值
                    }
                }
            }
            return model;
        }

        /// <summary>
        /// 返回指定列
        /// </summary>
        public string GetValue(SqlConnection conn, SqlTransaction trans, int id, string fileName)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 1 " + fileName + " from dt_company");
            strSql.Append(" where id=" + id);
            string title = Convert.ToString(DbHelperSQL.GetSingle(conn, trans, strSql.ToString()));
            if (string.IsNullOrEmpty(title))
            {
                return "";
            }
            return title;
        }


        #endregion        
    }
}

